package com.game.server.db.dao;

import com.game.majiang.config.LogManager;
import com.game.server.db.Parameter;
import com.game.server.db.ParameterType;
import com.game.server.db.SqlHelper;
import com.game.server.db.entity.TableUser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.sql.rowset.CachedRowSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

public class XyGameLogDao {

    /**
     * @param tabid      桌子号
     * @param cid        创建者ID
     * @param tablename  桌子名称
     * @param clubid     桌子的俱乐部id
     * @param pi         底皮
     * @param gametime   游戏时间
     * @param tableUsers 桌子内参与过游玩的玩家
     */
    public static void insertInto(int tabid, int cid, String tablename, int clubid, int pi, int gametime, List<TableUser> tableUsers,long tableonly) {
        List<String> gameplayers = new ArrayList<>();
        for (TableUser tableUser : tableUsers) {
            gameplayers.add(tableUser.getUid() + "");
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        if (gameplayers.size() > 0) {
            String sql = "INSERT INTO xy_allgeme_log (cid,tableid,tablename,clubid,pi,gametime,gameplayers,createtime,tableonly) VALUES (?,?,?,?,?,?,?,?,?)";
            Parameter p1 = new Parameter(Types.INTEGER, cid, ParameterType.Input);
            Parameter p2 = new Parameter(Types.INTEGER, tabid, ParameterType.Input);
            Parameter p3 = new Parameter(Types.VARCHAR, tablename, ParameterType.Input);
            Parameter p4 = new Parameter(Types.INTEGER, clubid, ParameterType.Input);
            Parameter p5 = new Parameter(Types.INTEGER, pi, ParameterType.Input);
            Parameter p6 = new Parameter(Types.INTEGER, gametime, ParameterType.Input);
            Parameter p7 = new Parameter(Types.VARCHAR, String.join(",", gameplayers), ParameterType.Input);
            Parameter p8 = new Parameter(Types.TIMESTAMP, timestamp, ParameterType.Input);
            Parameter p9 = new Parameter(Types.BIGINT, tableonly, ParameterType.Input);
            int execute = SqlHelper.execute(sql, p1, p2, p3, p4, p5, p6, p7, p8,p9);
            if (execute > 0) {
                for (TableUser user : tableUsers) {
                    int win = user.getBalance() - user.getDairu();
                    String minGameLogsql = "INSERT INTO xy_mingeme_log (tableid,uid,dairu,bobo,cid,win,createtime,tableonly,shoushu) VALUES (?,?,?,?,?,?,?,?,?)";
                    Parameter mp1 = new Parameter(Types.INTEGER, tabid, ParameterType.Input);
                    Parameter mp2 = new Parameter(Types.INTEGER, user.getUid(), ParameterType.Input);
                    Parameter mp3 = new Parameter(Types.INTEGER, user.getDairu(), ParameterType.Input);
                    Parameter mp4 = new Parameter(Types.INTEGER, user.getBalance(), ParameterType.Input);
                    Parameter mp5 = new Parameter(Types.INTEGER, user.getCid(), ParameterType.Input);
                    Parameter mp6 = new Parameter(Types.INTEGER, win, ParameterType.Input);
                    Parameter mp7 = new Parameter(Types.TIMESTAMP, timestamp, ParameterType.Input);
                    Parameter mp8 = new Parameter(Types.BIGINT, tableonly, ParameterType.Input);
                    Parameter mp9 = new Parameter(Types.INTEGER, user.getShoushu(), ParameterType.Input);
                    SqlHelper.execute(minGameLogsql, mp1, mp2, mp3, mp4, mp5, mp6, mp7,mp8,mp9);
                }
            }
        }
    }

    public static JSONObject findTableId(String tableid,int type) {
        JSONObject jsonObject = new JSONObject();
        String allgamelogsql = "select cid,tableid,tablename,clubid,gametime from xy_allgeme_log where tableonly="+tableid;
        String mingamelogsql = "select uid,dairu,bobo,cid,win,shoushu from xy_mingeme_log where tableonly="+tableid;
        String unionChangesGuotasql = "";
        if (type==2){
            unionChangesGuotasql = "select cid,quota,(0) as to_uid  from xy_union_changes_quota where type = 5 and roomkey="+tableid;
        }
//        if (type==3){
//            unionChangesGuotasql = "select cid,quota,pid as to_uid from xy_club_changes_quota where type = 5 and roomkey="+tableid;
//        }
        CachedRowSet allGameresultSet = SqlHelper.getResultSet(allgamelogsql);
        try {
            if (allGameresultSet.next()){
                jsonObject.put("cid",allGameresultSet.getInt(1));
                jsonObject.put("tableid",allGameresultSet.getInt(2));
                jsonObject.put("tablename",allGameresultSet.getString(3));
                jsonObject.put("clubid",allGameresultSet.getInt(4));
                jsonObject.put("gametime",allGameresultSet.getInt(5));
                JSONArray array = new JSONArray();
                CachedRowSet minGameresultSet = SqlHelper.getResultSet(mingamelogsql);
                while (minGameresultSet.next()) {
                    JSONObject tempObj = new JSONObject();
                    tempObj.put("uid",minGameresultSet.getInt(1));
                    tempObj.put("dairu",minGameresultSet.getInt(2));
                    tempObj.put("bobo",minGameresultSet.getInt(3));
                    tempObj.put("cid",minGameresultSet.getInt(4));
                    tempObj.put("win",minGameresultSet.getInt(5));
                    tempObj.put("shoushu",minGameresultSet.getInt(6));
                    array.add(tempObj);
                }
                jsonObject.put("list",array);
                JSONArray array2 = new JSONArray();
                if (type==2){
                    CachedRowSet unionChangesGuotaSet = SqlHelper.getResultSet(unionChangesGuotasql);
                    while (unionChangesGuotaSet.next()) {
                        JSONObject tempObj = new JSONObject();
                        tempObj.put("cid",unionChangesGuotaSet.getInt(1));
                        tempObj.put("quota",unionChangesGuotaSet.getInt(2));
                        tempObj.put("to_uid",unionChangesGuotaSet.getInt(3));
                        array2.add(tempObj);
                    }
                }
                jsonObject.put("guotaList",array2);
            }
        } catch (SQLException e) {
            LogManager.getInstance().errorLog(e);
        }
        return jsonObject;
    }
    /**
     * 查询车型总日志
     * @param limit
     * @param page
     * @param clubid
     * @param userId
     * @param type
     * @return
     */
    public static JSONObject findPage(int limit, Integer page, Integer clubid, int userId, Integer type) {

        JSONObject jsonObject = new JSONObject();
        JSONArray array = new JSONArray();
        String where = "";
        if (type==1){
            where = " and gameplayers LIKE '%"+userId+"%' ";
        }
        if (type==2){
            where = " and cid = "+userId+" ";
        }
        if (type==3){
            where = " and clubid = "+clubid+" ";
        }
        String countSql = "select count(id) from xy_allgeme_log where 1=1"+ where;
        String sql = "select cid,tableid,tablename,clubid,pi,gametime,createtime,DATE_FORMAT(createtime,'%m月%d日'),IFNULL((select CONCAT(win,',',dairu) from xy_mingeme_log where uid="+userId+" and tableid=xg.tableid),'0,0'),tableonly from xy_allgeme_log as xg where 1=1 "+ where + " ORDER BY createtime desc LIMIT ?," + limit;
        Object scalar = SqlHelper.execScalar(countSql);
        int sumCount = Integer.parseInt(scalar.toString());
        int sumPage = (int) Math.ceil((double) sumCount/limit);
        page = page<1?1:page>sumPage?sumPage:page;
        page = page<1?1:page;
        Parameter p1 = new Parameter(Types.INTEGER, ((page-1)*limit), ParameterType.Input);
        CachedRowSet resultSet = SqlHelper.getResultSet(sql,p1);
        jsonObject.put("page",page);
        jsonObject.put("allpage",sumPage);
        jsonObject.put("allcount",sumCount);
        try {
            while (resultSet.next()) {
                JSONObject jsonData = new JSONObject();
                jsonData.put("cid", resultSet.getInt(1));
                jsonData.put("tableid",resultSet.getInt(2));
                jsonData.put("tablename",resultSet.getString(3));
                jsonData.put("clubid",resultSet.getInt(4));
                jsonData.put("pi",resultSet.getInt(5));
                jsonData.put("gametime",resultSet.getInt(6));
                jsonData.put("gameendtime",resultSet.getTimestamp(7).getTime());
                jsonData.put("gameenddate",resultSet.getString(8));
                jsonData.put("windairu",resultSet.getString(9));
                jsonData.put("tableonly",resultSet.getString(10));
                array.add(jsonData);
            }
        } catch (SQLException e) {
            LogManager.getInstance().errorLog(e);
        }
        jsonObject.put("array",array);
        return jsonObject;
    }
}
